package com.cy.jt.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder PasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名从数据库查询用户信息
        if (!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名或密码输入错误!");
        }
        //2.将用户信息封装到UserDetails对象中并返回
        //自定义密码测试
        String encodePwd=PasswordEncoder.encode("123456");//加密
        //模拟权限信息
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList
                ( "ROLE_admin,ROLE_normal,sys:res:retrieve,sys:res:create");

        User user = new User(username, encodePwd, grantedAuthorities);
        return user;
    }
}
